<template>
  <el-select
    placeholder="工具箱"
    style="width: 100px"
    v-model="selected"
    @change="handleToolChange"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      style="color: dimgray"
    />
  </el-select>
</template>

<script setup>
import { ref, inject, onUnmounted } from 'vue'

const options = [
  { value: '1', label: '测量距离' },
  { value: '2', label: '测量面积' },
  { value: '3', label: '关闭测量' },
  { value: '4', label: '导出图片' },
]
const selected = ref('')
const map = inject('mapInstance', null)
let drawInteraction = null
let drawLayer = null

function clearDraw() {
  if (drawInteraction && map?.value) {
    map.value.removeInteraction(drawInteraction)
    drawInteraction = null
  }
  if (drawLayer && map?.value) {
    map.value.removeLayer(drawLayer)
    drawLayer = null
  }
}

function handleToolChange(val) {
  if (!map?.value) return
  clearDraw()
  if (val === '1' || val === '2') {
    drawLayer = new ol.layer.Vector({
      source: new ol.source.Vector(),
      style: new ol.style.Style({
        stroke: new ol.style.Stroke({ color: '#ff6600', width: 2 }),
        fill: new ol.style.Fill({ color: 'rgba(255,102,0,0.1)' }),
        image: new ol.style.Circle({
          radius: 5,
          fill: new ol.style.Fill({ color: '#ff6600' }),
        }),
      }),
    })
    map.value.addLayer(drawLayer)
    drawInteraction = new ol.interaction.Draw({
      type: val === '1' ? 'LineString' : 'Polygon',
      source: drawLayer.getSource(),
    })
    map.value.addInteraction(drawInteraction)
    drawInteraction.on('drawend', (evt) => {
      const geom = evt.feature.getGeometry()
      if (val === '1') {
        const length = ol.sphere.getLength(geom)
        alert('距离: ' + length.toFixed(2) + ' 米')
      } else {
        const area = ol.sphere.getArea(geom)
        alert('面积: ' + area.toFixed(2) + ' 平方米')
      }
    })
  } else if (val === '3') {
    // 关闭测量，已清除
  } else if (val === '4') {
    map.value.once('postcompose', function (event) {
      const canvas = event.context.canvas
      const url = canvas.toDataURL('image/png')
      const a = document.createElement('a')
      a.href = url
      a.download = 'map.png'
      a.click()
    })
    map.value.renderSync()
  }
}

onUnmounted(() => {
  clearDraw()
})
</script>

<style scoped lang="scss">
.work-box {
  display: flex;
  cursor: pointer;
}
</style>
